package ua.com.softway.db;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import junit.framework.TestCase;

import org.apache.log4j.Logger;

public abstract class DatabaseTestCase extends TestCase {
    private final static Logger log = Logger.getLogger(DatabaseTestCase.class);
    
    @Override
    protected void setUp() throws Exception {
        Persistence.init();
        
        EntityManagerFactory entityManagerFactory = Persistence.getEntityManagerFactory();
        
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        Persistence.setCurrentEntityManager(entityManager);
        
        entityManager.getTransaction().begin();
    }
    
    @Override
    protected void tearDown() throws Exception {
        try {
            EntityManager em = Persistence.current();
            
            if (em.getTransaction().isActive()) { 
                em.flush();
                
                if (em.getTransaction().getRollbackOnly())
                    em.getTransaction().rollback();
                else
                    em.getTransaction().commit();
            }
    
            em.getTransaction().begin();
            em.createNativeQuery("shutdown").executeUpdate();
            em.getTransaction().commit();
            
            em.close();
            
            Persistence.setCurrentEntityManager(null);
            
            Persistence.getEntityManagerFactory().close();
        } catch(Exception e) {
            // ignore to not eat exception from the code
            log.warn("Can't close persistence", e);
        }
    }
    
    public void flush() {
        Persistence.current().flush();
    }
    
    public void persist(Object o) {
        Persistence.current().persist(o);
    }
}
